package fx.beer;

import beans.Beer;
import dao.DaoBeer;
import fx.Home;
import fx.judge.JudgeController;
import fx.menu.MenuController;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import utils.ImageUtils;

public class BeerController implements Initializable {

    Beer beer;
    DaoBeer dao;
    Home application;
    File file;
    @FXML
    private ResourceBundle resources;
    @FXML
    private URL location;
    @FXML
    private Button btnFile;
    @FXML
    private Button btnSave;
    @FXML
    private Button btnCancel;
    @FXML
    private TextField textDescription;
    @FXML
    private TextField textImage;
    @FXML
    private TextField textMark;
    @FXML
    private TextField textName;
    @FXML
    private TextField textPercentage;
    @FXML
    private Label lblErrorName;
    @FXML
    private Label lblErrorMark;
    @FXML
    private Label lblErrorFile;
    @FXML
    private Label lblErrorAlcoholic;

    @FXML
    void cancel(ActionEvent event) {
        MenuController menu;
        try {
            menu = (MenuController) application.replaceSceneContent("menu/menu.fxml", Home.MENUWIDTH, Home.MENUHEIGTH, "BJCP-Scoresheet");
            menu.setMessage("sucess", "Welcome " + Home.loggedUser.getName());
            menu.setApp(application);
        } catch (Exception ex) {
            Logger.getLogger(JudgeController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @FXML
    void saveBeer(ActionEvent event) {
        Boolean save = true;
        if (textMark.getText().trim().isEmpty()) {
            lblErrorMark.setText("Required field");
            lblErrorMark.setVisible(true);
            save = false;
        }
        if (textName.getText().trim().isEmpty()) {
            lblErrorName.setText("Required field");
            lblErrorName.setVisible(true);
            save = false;
        }
        if (textPercentage.getText().trim().isEmpty()) {
            lblErrorAlcoholic.setText("Required field");
            lblErrorAlcoholic.setVisible(true);
            save = false;
        }
        if (textImage.getText().trim().isEmpty()) {
            lblErrorFile.setText("Required field");
            lblErrorFile.setVisible(true);
            save = false;
        }
        if (!save) {
            return;
        }
        beer = new Beer();
        beer.setDescription(textDescription.getText());
        beer.setMark(textMark.getText());
        beer.setAlcoholicPercentage(Float.parseFloat(textPercentage.getText()));
        beer.setName(textName.getText());
        beer.setImage(file.getAbsolutePath());
        dao = new DaoBeer();
        dao.save(beer);

        try {
            MenuController menu = (MenuController) application.replaceSceneContent("menu/menu.fxml", Home.MENUWIDTH, Home.MENUHEIGTH, "BJCP-Scoresheet");
            menu.setMessage("success", "Beer registered successfully");
            menu.setApp(application);
        } catch (Exception ex) {
            Logger.getLogger(BeerController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @FXML
    void initialize() {
        assert btnFile != null : "fx:id=\"btnFile\" was not injected: check your FXML file 'Beer.fxml'.";
        assert btnSave != null : "fx:id=\"btnSave\" was not injected: check your FXML file 'Beer.fxml'.";
        assert textDescription != null : "fx:id=\"textDescription\" was not injected: check your FXML file 'Beer.fxml'.";
        assert textImage != null : "fx:id=\"textImage\" was not injected: check your FXML file 'Beer.fxml'.";
        assert textMark != null : "fx:id=\"textMark\" was not injected: check your FXML file 'Beer.fxml'.";
        assert textName != null : "fx:id=\"textName\" was not injected: check your FXML file 'Beer.fxml'.";
        assert textPercentage != null : "fx:id=\"textPercentage\" was not injected: check your FXML file 'Beer.fxml'.";
        assert lblErrorAlcoholic != null : "fx:id=\"textPercentage\" was not injected: check your FXML file 'Beer.fxml'.";
        assert lblErrorName != null : "fx:id=\"textPercentage\" was not injected: check your FXML file 'Beer.fxml'.";
        assert lblErrorFile != null : "fx:id=\"textPercentage\" was not injected: check your FXML file 'Beer.fxml'.";
        assert lblErrorMark != null : "fx:id=\"textPercentage\" was not injected: check your FXML file 'Beer.fxml'.";
        textMark.setOnKeyPressed(markEventHandler);
        textName.setOnKeyPressed(nameEventHandler);
        textPercentage.setOnKeyPressed(percentageEventHandler);
        try {
            FileInputStream saveImage = new FileInputStream(System.getProperty("user.dir") + "\\src\\fx\\css\\images\\save.png");
            Image imageSave = new Image(saveImage);
            btnSave.setGraphic(new ImageView(imageSave));
            FileInputStream cancelImage = new FileInputStream(System.getProperty("user.dir") + "\\src\\fx\\css\\images\\cancel.png");
            Image imageCancel = new Image(cancelImage);
            btnCancel.setGraphic(new ImageView(imageCancel));
        } catch (FileNotFoundException ex) {
            System.out.println("Erro imagem");
        }
    }
    final EventHandler<KeyEvent> markEventHandler =
            new EventHandler<KeyEvent>() {
        public void handle(final KeyEvent keyEvent) {
            KeyCode code = keyEvent.getCode();
            if (code.isDigitKey() || code.isKeypadKey() || code.isLetterKey()) {
                lblErrorMark.setVisible(false);
            }
        }
    };
    final EventHandler<KeyEvent> nameEventHandler =
            new EventHandler<KeyEvent>() {
        public void handle(final KeyEvent keyEvent) {
            KeyCode code = keyEvent.getCode();
            if (code.isDigitKey() || code.isKeypadKey() || code.isLetterKey()) {
                lblErrorName.setVisible(false);
            }
        }
    };
    final EventHandler<KeyEvent> percentageEventHandler =
            new EventHandler<KeyEvent>() {
        public void handle(final KeyEvent keyEvent) {
            KeyCode code = keyEvent.getCode();
            if (code.isDigitKey() || code.isKeypadKey() || code.isLetterKey()) {
                lblErrorAlcoholic.setVisible(false);
            }
        }
    };

    @FXML
    void fileChooser(ActionEvent event) {
        Stage stage = new Stage();
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Open Resource File");
        file = fileChooser.showOpenDialog(stage);
        String msg = ImageUtils.validateIsImageAndExists(file);
        if (msg == null) {
            textImage.setText(file.getAbsolutePath());
            lblErrorFile.setVisible(false);
        } else {
            lblErrorFile.setText(msg);
            lblErrorFile.setVisible(true);
        }

    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        initialize();
        //    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public void setApp(Home application) {
        this.application = application;
    }
}
